from fastapi import APIRouter, Depends, HTTPException
from typing import List

from basic import BaseSchema, logger
from service import RepoService, IRepoService

router = APIRouter(prefix="/repos", tags=["repos"])

########################################
class RepoMountRequest(BaseSchema):
    name: str

class RepoMountResponse(BaseSchema):
    repo_key: str

@router.post("/mount", response_model=RepoMountResponse)
async def mount_repo(
    params: RepoMountRequest, 
    service: IRepoService = Depends(RepoService)
):
    try:
        return await service.mount_repo(params.name)
    except Exception as e:
        logger.error(f"Error mounting repository: {e}")
        raise HTTPException(status_code=400, detail=str(e))

class RepoUnmountRequest(BaseSchema):
    repo_key: str

class RepoUnmountResponse(BaseSchema):
    name: str

@router.post("/unmount", response_model=RepoUnmountResponse)
async def unmount_repo(
    params: RepoUnmountRequest, 
    service: IRepoService = Depends(RepoService)
):
    try:
        return await service.unmount_repo(params.repo_key)
    except Exception as e:
        logger.error(f"Error unmounting repository: {e}")
        raise HTTPException(status_code=400, detail=str(e))

class RepoUpdateRequest(BaseSchema):
    repo_key: str
    update_key: str
    update_value: str

class RepoUpdateResponse(BaseSchema):
    repo_key: str
    
@router.post("/update", response_model=RepoUpdateResponse)
async def update_repo(
    params: RepoUpdateRequest, 
    service: IRepoService = Depends(RepoService)
):
    try:
        return await service.update_repo(params.repo_key, params.update_key, params.update_value)
    except Exception as e:
        logger.error(f"Error updating repository: {e}")
        raise HTTPException(status_code=400, detail=str(e))

class RepoListResponseItem(BaseSchema):
    name: str
    repo_key: str
    entry_key: str
    
RepoListResponse = List[RepoListResponseItem]

@router.get("/list", response_model=RepoListResponse)
async def list_repos(
    service: IRepoService = Depends(RepoService)
):  
    try:
        return await service.list_repos()
    except Exception as e:
        logger.error(f"Error listing repositories: {e}")
        raise HTTPException(status_code=400, detail=str(e))
